const express = require("express");
const serveIndex = require("serve-index");
const os = require("os");
const { exec } = require("child_process");
// 复制中文
const iconv = require("iconv-lite");

// 是否含有中文
function isHasChinese(str) {
  return /.*[\u4e00-\u9fa5]+.*$/.test(str);
}

// 获取本机ip
function getIpAddress() {
  var ifaces = os.networkInterfaces();

  for (var dev in ifaces) {
    let iface = ifaces[dev];

    for (let i = 0; i < iface.length; i++) {
      let { family, address, internal } = iface[i];

      if (family === "IPv4" && address !== "127.0.0.1" && !internal) {
        return address;
      }
    }
  }
}

// 获取文件名
function getFileName(defaultFullPath = "") {
  const fullPath = defaultFullPath.replace(/(”|“)/g, "");

  let file_name = fullPath.replace(/(.*\\)*([^.]+).*/gi, "$2");
  let file_ext;
  let filePath = fullPath;

  if (/.+\./.test(fullPath)) {
    // 文件
    file_ext = fullPath.replace(/.+\./, "");
    filePath = fullPath.replace(`\\${file_name}.${file_ext}`, "");
  }

  // console.log("file_ext: ", file_ext, /.+\./.test(fullPath));
  // console.log("filePath: ", filePath);

  return {
    filePath,
    fileName: file_ext ? file_name + "." + file_ext : "",
  };
}

// 文件服务
function server(url, fileName) {
  const ipAddress = getIpAddress();

  const app = new express();
  app.use(express.static(url));
  app.use("/", serveIndex(url, { icons: true, view: "details" }));

  app.listen(8889, () => {
    let address = `http://${ipAddress}:8889/${fileName}`;

    if (isHasChinese(address)) {
      // 复制中文，否则会乱码
      exec("clip").stdin.end(iconv.encode(address, "gbk"));
    } else {
      exec("clip").stdin.end(address);
    }

    console.log(
      `当前共享地址为： ${address} （已复制到剪切板，ctrl+v直接粘贴）`
    );
  });
}

// 新增注册表
function addRegisterList(keyPath, value) {
  return new Promise((resolve, reject) => {
    try {
      const result = exec(`reg add ${keyPath} /d ${value} /f`);
      resolve(result);
    } catch (error) {
      reject(error);
    }
  });
}

module.exports = {
  server,
  getFileName,
  addRegisterList,
};
